//
//  EditAdderssVC.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/2/27.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "EditAdderssVC.h"
#import "LabelTFCell.h"
#import "TableBtnView.h"

#import "BLAreaPickerView.h"

#import "AddressModel.h"

@interface EditAdderssVC () 

@property (strong, nonatomic) NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (copy, nonatomic) ResultBlock resultBlock;

@end

@implementation EditAdderssVC

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray =[NSMutableArray array];
        NSArray *titles =@[@"联系人", @"手机号码", @"所在地区", @"详细地址"];
        NSArray *placeholders =@[@"收货人姓名", @"请输入您的联系电话", @"请选择地址", @"请输入您的详细地址"];
        NSArray *propertyName =@[@"recipients", @"recipientsPhone", @"", @"address"];
        for (NSInteger index =0; index<titles.count; index++) {
            NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithObjectsAndKeys:titles[index],
                                        @"title", placeholders[index],
                                        @"placeholder", @"", @"content",propertyName[index], @"propertyName", nil];
            [_dataArray addObject:dict];
        }
        
    }
    return _dataArray;
}

- (void)setAddressModel:(AddressModel *)addressModel {
    _addressModel = addressModel;
    NSArray *info = @[addressModel.recipients, addressModel.recipientsPhone, [NSString stringWithFormat:@"%@-%@-%@",addressModel.province, addressModel.city, addressModel.county], addressModel.address];
    for (NSUInteger i = 0; i < info.count; i++) {
        NSMutableDictionary *mutDic = self.dataArray[i];
        [mutDic setObject:info[i] forKey:@"content"];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 120;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 10)];
    headerView.backgroundColor =tableView.backgroundColor;
    return headerView;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 120)];
    footerView.backgroundColor =tableView.backgroundColor;
    
    TableBtnView *btmView =[TableBtnView loadNib:@"TableBtnView" frame:CGRectMake(0, 10, KScreenWidth, CGRectGetHeight(footerView.frame)-10)];
    btmView.backgroundColor =[UIColor clearColor];
    if (self.addressModel) {
        btmView.typeButton.selected = ((AddressModel *)self.addressModel).level;
    }
    [btmView didButtonClickBlock:^(UIButton *button) {
        if (button == btmView.typeButton) {
            button.selected =! button.selected;
        } else {
            [self submitAddressIsDefault:btmView.typeButton.selected];
        }
    }];
    [footerView addSubview:btmView];
    
    return footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LabelTFCell *cell =[tableView dequeueReusableCellWithIdentifier:@"LabelTFCell"];
    if (!cell) {
        cell =[LabelTFCell findCellWithIdentifier:@"LabelTFCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    if (indexPath.row ==2) {
        cell.viewType =RightViewType_Button;
        cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.viewType =RightViewType_TextField;
        cell.accessoryType =UITableViewCellAccessoryNone;
    }
    NSMutableDictionary *dataDict =_dataArray[indexPath.row];
    cell.dataDict =dataDict;
    [cell didButtonBlock:^(UIButton *button) {
        [self.view endEditing:NO];
        
        BLAreaPickerView *pickView = [[BLAreaPickerView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, IS_IPHONE_X?240:200)];
        [pickView sureButtonClickBlock:^(NSString *provinceTitle, NSString *cityTitle, NSString *areaTitle) {
            NSString *areaStr = [NSString stringWithFormat:@"%@-%@-%@",provinceTitle,cityTitle,areaTitle];
            [dataDict setObject:areaStr forKey:@"content"];
            [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }];
        [pickView bl_show];
        
    }];
    [cell TFEndChangeValueBlock:^(UITextField *TF) {
        [dataDict setObject:TF.text forKey:@"content"];
    }];
    return cell;
}

/// 提交地址
- (void)submitAddressIsDefault:(BOOL)defaul {
    NSLog(@"%@", defaul?@"YES":@"NO");
    [self.view endEditing:NO];
    NSMutableDictionary *upDic = [NSMutableDictionary dictionary];
    [upDic setObject:defaul?@(1):@(0) forKey:@"level"];
    NSInteger flag = 0;
    for (NSMutableDictionary *dict in self.dataArray) {
        NSString *title = dict[@"title"];
        NSString *contents = [dict[@"content"] stringByReplacingOccurrencesOfString:@" " withString:@""];
        // @[@"联系人", @"手机号码", @"所在地区", @"详细地址"];
        if (contents.length == 0) {
            ShowAlertTitle(([NSString stringWithFormat:@"%@不能为空", title]));
            flag = 1;
            break;
        } else {
            if ([dict[@"propertyName"] description].length > 0) {
                [upDic setObject:contents forKey:dict[@"propertyName"]];
            } else {
                NSArray *arr = [contents componentsSeparatedByString:@"-"];
                if (arr.count == 3) {
                    [upDic setObject:arr[0] forKey:@"province"];
                    [upDic setObject:arr[1] forKey:@"city"];
                    [upDic setObject:arr[2] forKey:@"county"];
                } else {
                    [upDic setObject:@"" forKey:@"province"];
                    [upDic setObject:@"" forKey:@"city"];
                    [upDic setObject:@"" forKey:@"county"];
                }
            }
        }
    }

    // 请求  falg == 1 代表 textfield 中有数据为空
    if (flag) {
        return;
    }
    
    if (self.addressModel) { // 编辑
        [upDic setObject:@(((AddressModel *)_addressModel).id) forKey:@"id"];
        [HttpUrl POST:@"address/update" dict:upDic hud:self.view isShow:YES WithSuccessBlock:^(id data) {
                
            [self.navigationController popViewControllerAnimated:YES];
            if (self.resultBlock) {
                self.resultBlock([data[@"success"] boolValue], _addressModel?YES:NO);
            }
            
        }];
    } else
    {
        [HttpUrl POST:@"address/addNewAddress" dict:upDic hud:self.view isShow:YES WithSuccessBlock:^(id data) {
            
            [self.navigationController popViewControllerAnimated:YES];
            if (self.resultBlock) {
                self.resultBlock([data[@"success"] boolValue], _addressModel?YES:NO);
            }
            
        }];
    }
  
}

- (void)addOrEditSuccessBlock:(ResultBlock)newBlock {
    self.resultBlock =newBlock;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
